﻿using fastdb.Db.storage;
using fastdb.Lexer;
using fastdb.Parser;

namespace fastdb.Db;

public interface IDataBase
{
    bool Open();

    Table EnsureTable(string tableName);

    string Execute(string sql);

    bool Save(Table table);

    bool Close();
}

public class DataBase : IDataBase
{
    //存储引擎
    private readonly StorageController _sc;

    //数据库管理的表
    private readonly Dictionary<string, Table> _tables   = new();

    public DataBase(string dbDataPath, string dbName)
    {
        _sc = new StorageController(dbDataPath);
        _sc.CreateDbStorage(dbName);
    }


    public bool Open()
    {
        return true;
    }

    public Table EnsureTable(string tableName)
    {
        if (!_tables.ContainsKey(tableName)) _tables.Add(tableName, new Table { Name = tableName });
        return _tables[tableName];
    }


    public string Execute(string sql)
    {
        var tokens = new SqlLexer().Scan(sql);

        var parser = new SqlParser();
        var sqlNode = parser.Parser(tokens);

        if (parser.Errors.Count > 0) return string.Join(" ", parser.Errors);

        var result = sqlNode.Compute(this);
        return result;
    }

    /// <summary>
    /// 保存表数据
    /// </summary>
    /// <param name="table"></param>
    /// <returns></returns>
    public bool Save(Table table)
    {
        if (!_tables.ContainsKey(table.Name)) return false;

        _sc.SaveTableData(table);

        return true;
    }

    public bool Close()
    {
        _sc.CloseDbStorage();
        return true;
    }
}